package com.wzq.service.impl;

import com.sun.mail.smtp.SMTPAddressFailedException;
import com.wzq.service.EmailService;
import org.apache.dubbo.config.annotation.Service;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;


import javax.mail.MessagingException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


/**
 * @author wzq.Jolin
 * @company none
 * @create 2020-09-14 12:57
 */
@Service
public class EmailServiceImpl implements EmailService {

    private static Logger log = LogManager.getLogger( EmailServiceImpl.class );

   @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;

    private static final String EMAIL_SUBJECT = "注册验证码";

    @Override
    public boolean email(String email, String code) {
        System.out.println( "email被调用到啦，email=" + email );

        String text = "您的验证码为：  " + code + "\r\n不要告诉别人哟";

        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper mimeMessageHelper = null;
            mimeMessageHelper = new MimeMessageHelper( mimeMessage, true );
            mimeMessageHelper.setFrom( new InternetAddress( "作业<" + from + ">" ) );
            mimeMessageHelper.setTo( email );
            mimeMessageHelper.setSubject( EMAIL_SUBJECT );
            mimeMessageHelper.setText( text, true );

            // 发送邮件
            mailSender.send( mimeMessage );
        } catch (SMTPAddressFailedException e) {
            log.error( "邮件发送失败，邮箱地址错误，检查邮箱输入是否有误 ex={}", e.getMessage(), e );
            return false;
        } catch (MessagingException e) {
            log.error( "邮件发送失败 ex={}", e.getMessage(), e );
            return false;
        }

        log.info( "邮件发送成功" );
        return true;
    }
}

